import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/components/images/image_view.dart';
import 'package:wallpaper/db/love_database.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/providers/setting_provider.dart';
import 'package:wallpaper/tools/route_animation.dart';
import 'dart:async';

class LovePage extends StatefulWidget {
  final String axis;
  const LovePage({super.key, required this.axis});

  @override
  State<LovePage> createState() => _LovePageState();
}

class _LovePageState extends State<LovePage> {
  List imgs = [];
  Timer? _resetTimer;

  Future<void> getData() async {
    var res =
        await context.read<LoveDatabase>().getAllLove('image', widget.axis);
    setState(() {
      imgs = res;
    });
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    _resetTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final SettingProvider setting = Provider.of<SettingProvider>(context);
    return Scaffold(
      floatingActionButton: SizedBox(
        height: 45,
        width: 45,
        child: FloatingActionButton(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50),
          ),
          child: Icon(Icons.delete, color: Colors.red),
          onPressed: () {
            showCupertinoDialog(
              //点击空白处取消
              barrierDismissible: true,
              context: context,
              builder: (context) {
                return CupertinoAlertDialog(
                  title: Text(S.of(context).s8),
                  content: Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(S.of(context).s9),
                  ),
                  actions: [
                    CupertinoDialogAction(
                      child: Text(S.of(context).s10),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    CupertinoDialogAction(
                      child: Text(S.of(context).s11),
                      onPressed: () {
                        context
                            .read<LoveDatabase>()
                            .removeAllLove('image', widget.axis);
                        setState(() {
                          imgs = [];
                        });
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          },
        ),
      ),
      body: imgs.isEmpty
          ? Empty()
          : Padding(
              padding: EdgeInsets.all(setting.padding),
              child: CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                    child: SizedBox(
                      height: MediaQuery.of(context).padding.top,
                    ),
                  ),
                  SliverGrid(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: widget.axis == 'horizontal'
                          ? OptionsBase().horizontalColumns(context)
                          : OptionsBase().imageColumns(context),
                      childAspectRatio: widget.axis == 'horizontal' ? 1.7 : 0.7,
                      mainAxisSpacing: setting.padding,
                      crossAxisSpacing: setting.padding,
                    ),
                    delegate: SliverChildBuilderDelegate(
                      childCount: imgs.length,
                      (context, index) =>
                          buildItem(context, index, setting.radius),
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  Widget buildItem(BuildContext context, int index, double radius) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(radius),
      child: GestureDetector(
        onTap: () {
          RouteAnimation().animateRoute(
              context,
              ImageView(
                images: imgs,
                selectedIndex: index,
                resetGetdata: () {
                  // 等待 500 ms，重新获取数据
                  _resetTimer?.cancel(); // 取消之前的定时器（如果存在）
                  _resetTimer = Timer(Duration(milliseconds: 500), () {
                    if (mounted) {
                      getData();
                    }
                  });
                },
              ));
        },
        child: Stack(alignment: Alignment.bottomLeft, children: [
          SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: ImageLoad(
                key: UniqueKey(), // 添加唯一的 key
                imageUrl: imgs[index].smallPath),
          ),
          if (imgs[index].tags != "")
            Container(
                width: double.infinity,
                padding: EdgeInsets.all(3),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.black.withOpacity(0),
                      Colors.black.withOpacity(1),
                    ],
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5),
                  child: Text(
                    imgs[index].tags,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                )),
        ]),
      ),
    );
  }
}
